package com.jf.mall.service;

import com.jf.mall.dao.FurnitureDAO;
import com.jf.mall.dao.OrderDAO;
import com.jf.mall.dao.OrderItemDAO;
import com.jf.mall.dao.impl.FurnitureImpl;
import com.jf.mall.dao.impl.OrderImpl;
import com.jf.mall.dao.impl.OrderItemImpl;
import com.jf.mall.domain.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-10-10
 * Time:20:56
 */
public class OrderService {
    private final OrderDAO orderDAO = new OrderImpl();
    private final OrderItemDAO orderItemDAO = new OrderItemImpl();
    private final FurnitureDAO furnitureDAO = new FurnitureImpl();
    public String generateOrder(ShoppingCart shoppingCart) {
        //根据shoppingCart构建order
        Integer userId = shoppingCart.getUserId();
        BigDecimal amount = shoppingCart.getTotalPrice();
        Order order = new Order(userId, amount);
        orderDAO.insertOrder(order);
        //根据shoppingCart构建orderItem 并更新furniture
        List<Commodity> commodities = shoppingCart.getCommodities();
        String orderId = order.getId();
        for (Commodity commodity : commodities) {
            OrderItem orderItem = new OrderItem(orderId, commodity);
            orderItemDAO.insertOrderItem(orderItem);
            Integer furnitureId = commodity.getFurnitureId();
            Integer count = commodity.getCount();
            Furniture furniture = furnitureDAO.queryFurnitureById(furnitureId);
            furniture.setSale(furniture.getSale() + count);
            furniture.setStock(furniture.getStock() - count);
            furnitureDAO.updateFurniture(furniture);
        }
        return orderId;
    }
    public List<Order> getOrders(User user) {
        return orderDAO.queryOrder(user.getId());
    }
    public List<OrderItem> getOrderItems(String orderId) {
        return orderItemDAO.getOrderItemsByOrderId(orderId);
    }
}
